import { Watcher } from "./watcher";
let flush: boolean = false;
let has: { [key: number]: boolean } = {};
let queue: Array<Watcher> = [];
let index = 0;
let wait = false;
export function queueWatcher(watcher: Watcher) {
  let id = watcher.id;
  if (has[id] == null) {
    has[id] = true;
    if (!flush) {
      queue.push(watcher);
    } else {
      let length = queue.length - 1;
      while (length > index && queue[length].id > watcher.id) {
        length--;
      }
      queue.splice(length + 1, 0, watcher);
    }
    if (!wait) {
      wait = true;
      nextTick(FlushSchedulerQueue);
    }
  }
}

function FlushSchedulerQueue() {
  flush = true;
  let watcher, id;
  queue.sort((a, b) => a.id - b.id);
  for (index = 0; index < queue.length; index++) {
    watcher = queue[index];
    id = watcher.id;
    if (watcher.before) {
      watcher.before();
    }
    watcher.run();
  }
  RestScheduler();
}
function RestScheduler() {
  flush = false;
  wait = false;
  has = {};
  queue.length = 0;
}
function nextTick(cb: () => void) {
  let p = Promise.resolve();
  p.then(cb);
}
